package request;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.function.BiConsumer;

/**
 * 获取请求参数的通用方法：
 *                      String getParameter(String name):根据名称获取参数的值
 *                      String[] getParameterValues(String name):根据名称获取参数的值的数组
 *                      Enumeration<String> getParameterNames:获取所有的参数名称
 *                      Map<String,String[]> getParameterMap():获取所有参数的map集合
 * 中文乱码问题的解决：
 *                  GET方式不会出现中文乱码
 *                  POST方式需要设置流的编码: request.setCharacterEncoding("UTF-8");
 *
 *
 */
@WebServlet(value = "/request_demo4")
public class request_demo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置流编码
        request.setCharacterEncoding("UTF-8");

        //1.根据名称获取参数的值
        System.out.println("------------------1-----------------");
        String parameter1 = request.getParameter("username");
        String parameter2 = request.getParameter("password");
        System.out.println("username="+parameter1);
        System.out.println("password="+parameter2);
        System.out.println("------------------2-----------------");
        //2.根据名称获取参数的值的数组
        String[] hobbies = request.getParameterValues("hobby");
        for (String hobby : hobbies) {
            System.out.println(hobby);
        }
        System.out.println("------------------3-----------------");
        //3.获取所有的参数名称
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()){
            String element = names.nextElement();
            System.out.println(element);
            System.out.println(request.getParameter(element));
            System.out.println("-------------------");
        }
        System.out.println("------------------4-----------------");
        //4.获取所有参数的map集合
        Map<String, String[]> parameterMap = request.getParameterMap();
        parameterMap.forEach(new BiConsumer<String, String[]>() {
            @Override
            public void accept(String s, String[] strings) {
                for (String string : strings) {
                    System.out.println(s+"====>"+string);
                }
            }
        });

    }
}
